package com.drone.drone_server.controller;

import com.drone.drone_server.api.ApiResponse;
import com.drone.drone_server.dao.DroneDao;
import com.drone.drone_server.entity.Drone;
import com.drone.drone_server.entity.FireVideo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/drone")
public class DroneController {
    @Autowired
    private DroneDao droneDao;
    @PutMapping("/updateStatue")
    public ApiResponse updateStatue(
            @RequestParam("drone_id") Integer droneId,
            @RequestParam("drone_status") String statusValue) {

        try {
            // 1. 校验参数非空
            if (droneId == null || statusValue == null) {
                return ApiResponse.fail("参数不能为空");
            }

            Drone drone = droneDao.selectById(droneId);
            if (drone == null) {
                return ApiResponse.fail("无人机不存在");
            }
            Drone.Status newStatus = parseDroneStatus(statusValue);



            // 4. 执行状态更新
            int result = droneDao.updateStatus(droneId, newStatus);
            if (result > 0) {
                return ApiResponse.success("状态更新成功");
            }
            return ApiResponse.fail("状态更新失败");

        } catch (IllegalArgumentException e) {
            return ApiResponse.fail("无效状态值：" + statusValue);
        } catch (Exception e) {
            return ApiResponse.fail("服务器错误：" + e.getMessage());
        }
    }

    @GetMapping("/getDrone")
    public ApiResponse getDrone(@RequestParam("drone_id") Integer droneId) {
        return ApiResponse.success(droneDao.selectById(droneId));
    }

    private Drone.Status parseDroneStatus(String statusValue) {
        for (Drone.Status status : Drone.Status.values()) {
            if (status.getValue().equals(statusValue)) {
                return status;
            }
        }
        return null;
    }

}
